//
//  HESickbedViewController.m
//  HealthElderly
//
//  Created by 吴欧 on 2021/5/12.
//  Copyright © 2021 honglutec. All rights reserved.
//

#import "HESickbedViewController.h"
#import "HESickedModel.h"
#import "DLRadioButton.h"
#import "HESheetListView.h"
#import "HEApplyModel.h"
#import "HESickedCreateOrderViewController.h"
#import "HESickedModel.h"
#import "HESickbedPlanItemCell.h"
#import "HESickbedDetailViewController.h"

@interface HESickbedViewController ()<HESheetListViewDelegate , UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) GDTableView *tableView;

@property (nonatomic, strong) HESickedModel *sickedModel;

@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, strong) UILabel *resLb;

@property (nonatomic, strong) QMUIFillButton *applyBtn;

// 约束参照视图,也是容器视图
@property (nonatomic, strong) UIView *contentView;

@property (nonatomic, strong) DLRadioButton *radioBtn;

/// 服务机构
@property (nonatomic, strong) NSMutableArray <HEApplyModel *>*serverOrgs;

@end

@implementation HESickbedViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"居家医养";
    
    [self loadData];
    [self loadServerOrgData];
}

#pragma mark - load data
- (void)loadData {
    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KsickbedInfo parameters:@{} success:^(id  _Nonnull responseObject) {
        DLog(@"%@", [responseObject mj_JSONString])
        HEResponse *respone = [HEResponse mj_objectWithKeyValues:responseObject];
        self.sickedModel = [HESickedModel mj_objectWithKeyValues:respone.data];
        if (!respone.data) {
            [self initSignView];
        }
        else if ([@"0" isEqualToString:self.sickedModel.apply_state]) {// 申请中
            [self initSignView];
        }
        else if ([@"1" isEqualToString:self.sickedModel.apply_state]) {// 同意
            [self initServerListView];
        }
        else if ([@"2" isEqualToString:self.sickedModel.apply_state]) {// 拒绝
            [self initSignView];
        }
         
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

- (void)loadServerOrgData {
    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KhomeOrg parameters:@{} success:^(id  _Nonnull responseObject) {
        DLog(@"%@", [responseObject mj_JSONString])
        HEArrayResponse *respone = [HEArrayResponse mj_objectWithKeyValues:responseObject];
        self.serverOrgs = [NSMutableArray arrayWithArray:[HEApplyModel mj_objectArrayWithKeyValuesArray:respone.data]];
 
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

#pragma mark - init ui
- (void)initSignView {
    
    if (_applyBtn) {
        [self refreshUI];
        return;
    }
    
    // 1. 添加scrollView
    [self.view addSubview:self.scrollView];
    // 2. 添加参照视图
    [self.scrollView addSubview:self.contentView];
    
    
    // 布局子控件
    // 设置scrollView约束
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(ZXNavBarHeight, 0, 0, 0));
    }];
    
    // 设置参照视图的约束
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.scrollView);
        make.width.equalTo(self.scrollView);
        make.height.mas_greaterThanOrEqualTo(KScreenHeight - ZXNavBarHeight - ZXSafeAreaBottom);
//        make.height.greaterThanOrEqualTo(@0.0f);
    }];
    
    
    UILabel *titleLb = [UILabel new];
    titleLb.text = @"申请须知";
    titleLb.font = DYBlodFont(25);
    titleLb.textAlignment = NSTextAlignmentCenter;
    [self.contentView addSubview:titleLb];

    QMUITextView *textView = [QMUITextView new];
    // 限制可输入的字符长度
    textView.maximumTextLength = 1500;
    textView.font = DYFont(17);
    textView.textColor = CNavLightBlackColor;
    textView.text = @"1.提供的患者资料情况属实。\n2.提供患者有效的通信联络方式，确定联系人，保证通讯联系畅通。\n3.患者病情有变化及时通知医生，病情不适宜在家治疗时应遵照责任医生要求及时转诊。\n4.配合责任医生、护士对患者的治疗。\n5.按收费标准支付费用。\n6.按要求办理建床、撤床手续。";
    textView.typingAttributes = @{NSFontAttributeName: DYFont(17),
                                       NSParagraphStyleAttributeName: [NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight:20]
    };
    textView.scrollEnabled = NO;
    textView.backgroundColor = KWhiteColor;
    textView.editable = NO;
    [self.contentView addSubview:textView];
    
    
    // 协议
    YYLabel *notesPLb = [[YYLabel alloc] init];
    notesPLb.textVerticalAlignment = YYTextVerticalAlignmentTop;
    notesPLb.textAlignment = NSTextAlignmentLeft;
    notesPLb.userInteractionEnabled = YES;
    [_contentView addSubview:notesPLb];

    NSDictionary *attributes = @{NSFontAttributeName:DYFont(17), NSForegroundColorAttributeName: CNavLightBlackColor};
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:@"  详请请见《居家医养建床知情同意书》" attributes:attributes];
    //设置高亮色和点击事件
    [text yy_setTextHighlightRange:[[text string] rangeOfString:@"《居家医养建床知情同意书》"] color:CNavBgColor backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        [self toSeeProtcal:@"https://www.honglutec.com/platform-rules/sick_bed_rule.html"];
    }];
    notesPLb.numberOfLines = 0;
    notesPLb.attributedText = text;
    
    // 勾选
    _radioBtn = [DLRadioButton new];
    _radioBtn.tag = 1;
    _radioBtn.marginWidth = 10;
    _radioBtn.iconSize = 30;
    _radioBtn.multipleSelectionEnabled = YES;
    _radioBtn.icon = [UIImage imageNamed:@"check_box_unsel"];
    _radioBtn.iconSelected = [UIImage imageNamed:@"check_box_sel"];
    [_radioBtn setTitle:@"我已认真阅读并接受上述管理条例" forState:UIControlStateNormal];
    [_radioBtn setTitleColor:CNavLightBlackColor forState:UIControlStateNormal];
    _radioBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    _radioBtn.titleLabel.font = DYFont(17);
    [self.contentView addSubview:_radioBtn];
    
    // 拒绝
    UILabel *resLb = [UILabel new];
    resLb.font = DYBlodFont(17);
    resLb.textColor = CPriceColor;
    resLb.numberOfLines = 0;
    _resLb = resLb;
    [self.contentView addSubview: resLb];
    
    // 立即申请
    QMUIFillButton *applyBtn = [[QMUIFillButton alloc] initWithFillType:QMUIFillButtonColorBlue];
    _applyBtn = applyBtn;
    applyBtn.titleLabel.font = DYBlodFont(17);
    [applyBtn setBackgroundColor:CNavBgColor];
    [applyBtn setTitle:@"立即申请" forState:UIControlStateNormal];
    [self.contentView addSubview: applyBtn];
    [applyBtn addTarget:self action:@selector(applyClick) forControlEvents:UIControlEventTouchUpInside];
     
    [titleLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.contentView).offset(25);
        make.left.equalTo(self.contentView).offset(15);
        make.right.equalTo(self.contentView).offset(-15);
    }];
    
    [textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleLb.mas_bottom).mas_offset(15);
        make.left.equalTo(self.contentView).mas_offset(15);
        make.right.equalTo(self.contentView).mas_offset(-15);
    }];
  
    [notesPLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(textView.mas_bottom).mas_offset(15);
        make.left.equalTo(self.contentView).mas_offset(15);
        make.right.equalTo(self.contentView).mas_offset(-15);
    }];
    
    [_radioBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(notesPLb.mas_bottom).mas_offset(15);
        make.left.equalTo(self.contentView).mas_offset(15);
        make.right.equalTo(self.contentView).mas_offset(-15);
    }];
    
    [resLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_radioBtn.mas_bottom).mas_offset(15);
        make.left.equalTo(self.contentView).mas_offset(15);
        make.right.equalTo(self.contentView).mas_offset(-15);
    }];
    
    [applyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(resLb.mas_bottom).mas_offset(60);
        make.left.equalTo(self.contentView).mas_offset(40);
        make.right.equalTo(self.contentView).mas_offset(-40);
        make.height.mas_offset(45);
    }];
    
    [self refreshUI];
}

- (void)refreshUI {
    if ([@"0" isEqualToString:_sickedModel.apply_state]) {
        _resLb.hidden = YES;
        _resLb.text = @"";
        _radioBtn.selected = YES;
        _radioBtn.userInteractionEnabled = NO;
        _applyBtn.userInteractionEnabled = NO;
        [_applyBtn setTitle:@"申请中..." forState:UIControlStateNormal];
    }
    else if ([@"2" isEqualToString:_sickedModel.apply_state]) {
        _radioBtn.selected = YES;

        _resLb.text = @"申请已被拒绝，您可以选择机构重新提交申请";
        if (![DYTools isBlankString: _sickedModel.need_service]) {
            _resLb.text = [NSString stringWithFormat: @"申请已被拒绝（原因：%@），您可以选择机构重新提交申请", _sickedModel.need_service];
        }
    }
}

#pragma mark -

- (void)initServerListView {
    [self.view addSubview:self.tableView];
}

- (GDTableView *)tableView {
    if (!_tableView) {
        _tableView = [[GDTableView alloc] initWithFrame:CGRectMake(0, ZXNavBarHeight + 50 + 50, KScreenWidth, KScreenHeight - ZXNavBarHeight -50 -50) style:UITableViewStylePlain];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        _tableView.separatorColor = CSplitLineColor;
        _tableView.scrollsToTop = YES;
        _tableView.tableFooterView = [[UIView alloc] init];
        _tableView.backgroundColor = KWhiteColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
         
        [_tableView registerClass:[HESickbedPlanItemCell class] forCellReuseIdentifier: @"HESickbedPlanItemCell"];
        
        [self.view addSubview:_tableView];
        
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view).mas_offset(ZXNavBarHeight);
            make.left.equalTo(self.view);
            make.right.equalTo(self.view);
            make.bottom.equalTo(self.view).offset(-ZXSafeAreaBottom);
        }];
    }
    return _tableView;
}


#pragma mark - click
- (void)applyClick {
    if (!_radioBtn.isSelected) {
        [Dialog toastBottom:@"请认真阅读并勾选上述管理条例"];
        return;
    }
    
    HESheetListView *manageView = [HESheetListView new];
    manageView.dataSource = self.serverOrgs;
    manageView.title = @"选择服务机构";
    manageView.delegate = self;
    [manageView show];
}

- (void)toSeeProtcal:(NSString *)protcalName {
    NSURL * file = [NSURL URLWithString:protcalName];
    RootWebViewController *webView = [[RootWebViewController alloc] initWithUrl:file.absoluteString];
    webView.isShowCloseBtn = YES;
    webView.showPageTitle = YES;
    RootNavigationController *nav = [[RootNavigationController alloc] initWithRootViewController:webView];
    nav.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:nav animated:YES completion:nil];
}

#pragma mark - HESheetListViewDelegate
- (void)sheetListViewSelectItemWith:(HEApplyModel *)model {
    HESickedCreateOrderViewController *vc = [HESickedCreateOrderViewController new];
    vc.title = model.hospital_name;
    vc.serviceCategoryId = model.hospital_id;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _sickedModel.plans.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HESickbedPlanItemCell *cell = [_tableView dequeueReusableCellWithIdentifier: @"HESickbedPlanItemCell"];
    [cell configCellWithModel:_sickedModel.plans[indexPath.row] indexPath:indexPath];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [tableView fd_heightForCellWithIdentifier: @"HESickbedPlanItemCell" cacheByIndexPath:indexPath configuration:^(HESickbedPlanItemCell *cell) {
        [cell configCellWithModel:self.sickedModel.plans[indexPath.row] indexPath:indexPath];
    }];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *warp = [UIView new];
    warp.backgroundColor = CViewBgColor;
    warp.qmui_borderWidth = 1;
    warp.qmui_borderColor = CViewBgColor;
    warp.qmui_borderPosition = QMUIViewBorderPositionBottom;

    
    UILabel *serverNameLb = [UILabel new];
    serverNameLb.text = @"服务项目";
    serverNameLb.font = DYBlodFont(17);
    serverNameLb.textAlignment = NSTextAlignmentCenter;
    [warp addSubview:serverNameLb];
    
    UILabel *serverDateLb = [UILabel new];
    serverDateLb.text = @"服务日期";
    serverDateLb.font = DYBlodFont(17);
    serverDateLb.textAlignment = NSTextAlignmentCenter;
    [warp addSubview:serverDateLb];
    
    UILabel *serverStateLb = [UILabel new];
    serverStateLb.text = @"服务状态";
    serverStateLb.font = DYBlodFont(17);
    serverStateLb.textAlignment = NSTextAlignmentCenter;
    [warp addSubview:serverStateLb];
    
    UIView *line1 = [UIView new];
    line1.backgroundColor = CNavSubTitleColor;
    [warp addSubview:line1];
    
    UIView *line2 = [UIView new];
    line2.backgroundColor = CNavSubTitleColor;
    [warp addSubview:line2];
    
    [serverNameLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(warp);
        make.left.equalTo(warp);
        make.width.mas_equalTo(warp.mas_width).multipliedBy(0.4);
        make.bottom.equalTo(warp);
    }];
    
    [serverDateLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(warp);
        make.left.equalTo(serverNameLb.mas_right);
        make.width.mas_equalTo(warp.mas_width).multipliedBy(0.35);
        make.bottom.equalTo(warp);
    }];
    
    [serverStateLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(warp);
        make.left.equalTo(serverDateLb.mas_right);
        make.right.equalTo(warp);
        make.width.mas_equalTo(warp.mas_width).multipliedBy(0.25);
        make.bottom.equalTo(warp);
    }];
 
     
    [line1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(warp);
        make.left.equalTo(serverNameLb.mas_right).offset(-1);
        make.width.mas_equalTo(1);
        make.height.mas_equalTo(20);
    }];
    
    [line2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(warp);
        make.left.equalTo(serverDateLb.mas_right).offset(-1);
        make.width.mas_equalTo(1);
        make.height.mas_equalTo(20);
    }];
  
    
    return warp;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 50;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [_tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    HESickbedDetailViewController *vc = [HESickbedDetailViewController new];
    vc.model = _sickedModel.plans[indexPath.row];
    [self.navigationController pushViewController:vc animated:YES];
}
 
#pragma mark - getters
// scrollView
- (UIScrollView *)scrollView {
    if (_scrollView == nil) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.backgroundColor = KWhiteColor;
        _scrollView.alwaysBounceVertical = YES;
    }
    return _scrollView;
}

// 约束参照视图
- (UIView *)contentView {
    if (_contentView == nil) {
        _contentView = [[UIView alloc] init];
        _contentView.backgroundColor = KWhiteColor;
    }
    return _contentView;
}

@end
